package cn.kgc.service.impl;

import cn.kgc.config.WxConfig;
import cn.kgc.dto.Dto;
import cn.kgc.service.WxService;
import cn.kgc.utils.HttpclientUtils;
import cn.kgc.utils.UrlUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class WxServiceImpl implements WxService {


    @Autowired
    WxConfig wxConfig;

    @Override
    public Dto<Object[]> wxlogin(String code) {

        //1根据code获取accessToken
        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        Map accessTokenMap = getAccessTokenInfo(code);

        //2accessToken获取用户的个人信息
        Map userInfoMap = getUserInfoByAccessToken(accessTokenMap);

        //实现自身的业务
        //3.用户去数据库中查询wxUserId有没有这个openid，直接远程服务调用，List对象---空的--->没有这个对象


        //4.如果没有则插入一条这个用户dm_user的数据到数据库（实现一个注册的效果），将用户的头像信息放入dm_base中


        //5.根据用户的openId生成我们系统的token


        //6.将用户登录的信息放入redis中，并且还要把token放入redis中


        //7.返回我们系统生成的tokenVo+userVo(微信信息)



        return null;
    }

    public Map getUserInfoByAccessToken(Map map) {
        log.info("HttpResult--->Map：{}"+map);
        String accessToken= (String) map.get("access_token");
        String openId= (String) map.get("openid");

        StringBuffer userInfoUrl=new StringBuffer("https://api.weixin.qq.com/sns/userinfo?access_token=");
        userInfoUrl.append(accessToken);
        userInfoUrl.append("&openid=");
        userInfoUrl.append(openId);

        log.info("http请求获取微信用户信息参数=="+userInfoUrl.toString());
        //发送请求
        String userinfo = HttpclientUtils.get(userInfoUrl.toString());
        log.info("Http请求微信获取用户信息结果====={}",userinfo);
        Map userInfoMap = JSON.parseObject(userinfo, Map.class);
        return userInfoMap;
    }

    @Nullable
    public Map getAccessTokenInfo(String code) {
        StringBuffer urlStringBuffer=new StringBuffer("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
        urlStringBuffer.append(wxConfig.getAppid());
        urlStringBuffer.append("&secret=");
        urlStringBuffer.append(wxConfig.getSecret());
        urlStringBuffer.append("&code=");
        urlStringBuffer.append(code);
        urlStringBuffer.append("&grant_type=authorization_code");

        //发送http请求？  client--->URLUTILS

        //String httpresult = HttpclientUtils.get(urlStringBuffer.toString());
        //  log.info("HttpclientUtils发送http请求到微信，获取accessToken:{}"+httpresult);
        String s = UrlUtils.loadURL(urlStringBuffer.toString());
        log.info("UrlUtils发送http请求到微信，获取accessToken:{}",s);
        //String json ---->java Map
        return JSON.parseObject(s, Map.class);
    }
}
